package com.feather.tenia.adapter;

import java.util.HashMap;

import com.feather.common.db.DbFetcher;
import com.feather.common.db.DbSaver;
import com.feather.common.db.TypeMapping;

/**
 * @author flogyin
 */
public class TypeMappingAdapter implements TypeMapping {
	protected String						_null		= "";
	protected String						link		= "|";
	protected String						nilORna		= "nil/na";
	protected HashMap<String, DbFetcher>	fetchers	= new HashMap<String, DbFetcher>();
	protected HashMap<String, DbSaver>		savers		= new HashMap<String, DbSaver>();

	@Override
	public void register(DbFetcher fetcher) {
		if (fetcher != null && fetcher.getDbType() != null)
			this.fetchers.put(fetcher.getDbType().toLowerCase().trim(), fetcher);
	}

	@Override
	public void register(DbSaver saver) {
		if (saver != null && saver.getDbType() != null) {
			String dbType = saver.getDbType().toLowerCase().trim();
			if (saver.getJavaType() != null) {
				String key = saver.getJavaType().getName() + this.link + dbType;
				this.savers.put(key, saver);
			}
			String key = this._null + this.link + dbType;
			if (!this.savers.containsKey(key) || saver.matchNull()) {
				this.savers.put(key, saver);
			}
		}
	}

	/*
	 * @Override public void register(@SuppressWarnings("rawtypes") Class type,
	 * String dataType, DbSaver saver) { String jtName = type != null ?
	 * type.getName() : this._null; String key = jtName +this.link+ dataType;
	 * this.savers.put(key, saver); }
	 */

	@Override
	public DbFetcher lookup(String dataType) {
		String dataTypeName = dataType != null ? dataType.toLowerCase().trim() : this.nilORna;
		DbFetcher fetcher = this.fetchers.get(dataTypeName);
		return fetcher;
	}

	@Override
	public DbSaver lookup(@SuppressWarnings("rawtypes") Class type, String dataType) {
		String typeName = type != null ? type.getName() : this._null;
		String dataTypeName = dataType != null ? dataType.toLowerCase().trim() : this.nilORna;
		String key = typeName + this.link + dataTypeName;
		DbSaver saver = this.savers.get(key);
		return saver;
	}

	@Override
	public void clear() {
		this.fetchers.clear();
		this.savers.clear();
	}
}
